package com.uenpay.oem.data.modelImpl;

import android.content.Context;
import android.content.res.Resources;
import android.text.TextUtils;

import com.socks.library.KLog;
import com.uenpay.oem.MyApplication;
import com.uenpay.oem.data.bean.HomeFeaturesBean;
import com.uenpay.oem.data.model.IHomeFeatureModel;
import com.uenpay.util.common.ACache;
import com.uenpay.util.common.FileUtils;
import com.uenpay.util.json.JsonMananger;
import com.uenpay.util.rx.callback.CommonRequestCallback;
import com.uenpay.util.rx.callback.DataRequestCallback;

import junit.framework.Assert;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by liulou on 2017/4/20.
 * desc:
 */

public class HomeFeatureModel implements IHomeFeatureModel {

    private static final String TAG = "HomeFeatureModel";

    private static final String KEY_HOME_FEATURE_CACHE = "home_featrue_data";
    private static final String NAME_HOME_FEATURE_CONFIG = "home_feature.json";

    private ACache mCache;

    public HomeFeatureModel() {
        mCache = ACache.get(MyApplication.getAppContext());
    }

    @Override
    public void getHomeFeatures(final DataRequestCallback<HomeFeaturesBean> callback) {
        final boolean[] isFromCache = new boolean[]{true};
        Observable.just(KEY_HOME_FEATURE_CACHE).map(new Func1<String, String>() {
            @Override
            public String call(String s) {
                String json = mCache.getAsString(KEY_HOME_FEATURE_CACHE);
                if (json == null) {
                    json = FileUtils.getStringFromAsset(MyApplication.getAppContext(), NAME_HOME_FEATURE_CONFIG);
                    isFromCache[0] = false;
                }
                return json;
            }
        }).map(new Func1<String, HomeFeaturesBean>() {
            @Override
            public HomeFeaturesBean call(String json) {
                if (TextUtils.isEmpty(json)) return null;
                HomeFeaturesBean bean = JsonMananger.getInstance().jsonToBean(json, HomeFeaturesBean.class);
                if (!isFromCache[0]) {
                    setIconIdForFeature(bean);
                    mCache.put(KEY_HOME_FEATURE_CACHE, JsonMananger.getInstance().beanToJson(bean), Integer.MAX_VALUE);
                }
                return bean;
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<HomeFeaturesBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        callback.onError(e);
                    }

                    @Override
                    public void onNext(HomeFeaturesBean homeFeaturesBean) {
                        Assert.assertNotNull(homeFeaturesBean);
                        KLog.d(TAG, "show size:" + homeFeaturesBean.getGridShowFeature().size());
                        callback.onSuccess(homeFeaturesBean);
                    }
                });

    }

    @Override
    public void saveHomeFetures(HomeFeaturesBean bean, final CommonRequestCallback callback) {
        Observable.just(bean)
                .map(new Func1<HomeFeaturesBean, Object>() {
                    @Override
                    public Object call(HomeFeaturesBean homeFeaturesBean) {
                        String json = JsonMananger.getInstance().beanToJson(homeFeaturesBean);
                        KLog.d(TAG, "json=" + json);
                        mCache.put(KEY_HOME_FEATURE_CACHE, json, Integer.MAX_VALUE);
                        return null;
                    }
                }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Object>() {
                    @Override
                    public void call(Object o) {
                        callback.onSuccess();
                    }
                });
    }

    /**
     * 将json解析成对象，如果json不是从配置文件中读取，则根据对象中的iconName获取在R文件中对应id（iconId），最后将对象缓存
     *
     * @param json
     * @param isFromCache
     * @return
     */
    private HomeFeaturesBean getHomeFeatureByJson(String json, boolean isFromCache) {
        if (TextUtils.isEmpty(json)) return null;
        HomeFeaturesBean bean = JsonMananger.getInstance().jsonToBean(json, HomeFeaturesBean.class);
        if (!isFromCache) {
            setIconIdForFeature(bean);
            mCache.put(KEY_HOME_FEATURE_CACHE, JsonMananger.getInstance().beanToJson(bean), Integer.MAX_VALUE);
        }
        return bean;
    }

    /**
     * 从asset目录中获取对象没有iconId，根据资源名称获取资源id
     *
     * @param bean
     * @return
     */
    private HomeFeaturesBean setIconIdForFeature(HomeFeaturesBean bean) {
        Resources res = MyApplication.getAppContext().getResources();
        String pkgName = MyApplication.getAppContext().getPackageName();
        for (HomeFeaturesBean.Feature feature : bean.getTopFeature()) {
            int iconId = res.getIdentifier(
                    feature.getIconName(), "drawable", pkgName);
            feature.setIconId(iconId);
        }

        for (HomeFeaturesBean.Feature feature : bean.getGridShowFeature()) {
            int iconId = MyApplication.getAppContext().getResources().getIdentifier(
                    feature.getIconName(), "drawable", pkgName);
            feature.setIconId(iconId);
        }

        for (HomeFeaturesBean.Feature feature : bean.getGridHideFeature()) {
            int iconId = MyApplication.getAppContext().getResources().getIdentifier(
                    feature.getIconName(), "drawable", pkgName);
            feature.setIconId(iconId);
        }
        return bean;
    }
}
